'use strict';

const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");
/**
 * 
 * @param {*} npmName 
 * @param {*} registry 自定义镜像源
 */
function getNpmInfo(npmName, registry) {
    if(!npmName) return null;
    // TODO
    let registryUrl = registry || getDefaultRegitry(true);
    let packageUrl = urlJoin([registryUrl, npmName]);
    return axios.get(packageUrl).then(res => res.data);
}

function getDefaultRegitry(isOrginal = false) {
    return isOrginal ? "https://registry.npmjs.org" : "https://registry.npmjs.taonbao.org"
}

function getNpmVersion(npmName, registry) {
   return  getNpmInfo(npmName, registry).then(data =>  {
        const { versions } = data;
        console.log(Object.keys(versions));
        return Object.keys(versions);
    });
}

function getSemverVersion(npmName, registry) {
    return getNpmVersion(npmName, registry).then(versions => {
        versions.sort((a,b) => semver.gt(a,b) ? -1 : 0);
        return versions[0]
    });
}
module.exports = { 
    getNpmInfo, 
    getNpmVersion,
    getSemverVersion,
 };
